import React, { useEffect } from "react"
import { useState } from "react"
import { InfiniteScroll, Toast } from 'antd-mobile'
import { getHomeGoods } from '@/api/home'
import { GetCategoryGoods } from '@/api/category'
import { UserCollect } from '@/api/mine'
import { itemType } from "./type"

const Lists: React.FC<itemType> = ({getlist, type, menuID, page, setLoadingFlag}) => {
  const [goodList, setGoodList] = useState<any>([]) // 产品列表
  const [hasMore, setMore] = useState(true)
  const [pageNow,setPageNow] = useState(1) // 当前页
  const [error, setError] = useState(false);

  const init = async (pageCurrent: number) => {
    let res = null
    if(page === 'home') {// 首页
      res = await getHomeGoods(type, pageCurrent).catch((err) => {
        if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
          setError(true)
          setMore(false)
        }
      })
    } 
    else if(page === 'category') {// 分类
      res = await GetCategoryGoods(type, menuID, pageCurrent).catch((err) => {
        if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
          setError(true)
          setMore(false)
        }
      })
    } else {// 收藏
      res = await UserCollect(pageCurrent).catch((err) => {
        if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
          setError(true)
          setMore(false)
          setLoadingFlag()
        }
      })
    }

    if(res?.status === 200) {
      setError(false)
      setMore(true) 
      setPageNow(pageNow + 1) // page++
      if(page === 'collect') {
        setLoadingFlag()
        const data = res.data.data
        setGoodList((oldList: []) => [...oldList, ...data])
        if (res.data.data.length < 10 || res.data.data.length === 0) {
          setMore(false) 
        }
      } else {
        const data = res.data.goods.data
        setGoodList((oldList: []) => [...oldList, ...data])
        if (res.data.goods.data.length < 10 || res.data.goods.data.length === 0) {
          setMore(false) 
        }
      }
    }  
  }

  // 分类页面，点击不同的导航菜单, 重新设置右侧的list 当前页 是否还有更多
  // 因为menuID的变化 会执行 useEffect的更新阶段.  而antd-mobile的InfiniteScroll会随着组件的重新渲染而重新执行
  useEffect(() => {
    if(page === 'category') {
      setGoodList([])
      setMore(true)
      setPageNow(1)
    }
  }, [menuID])

  const loadMore =  async () => {
    await init(pageNow)
  } 

  return (
    <>
      {getlist(goodList)}
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
        {(hasMore, failed, retry) => {
          if(error) {
            return <span onClick={() => Toast.show({icon: 'loading', content: '加载中...', afterClose: () => retry()})}>加载失败, 重新加载</span>
          } else if(!hasMore) {
            return <span>没有更多了</span>
          } else {
            return <span>加载中...</span>
          }
        }}
      </InfiniteScroll>
    </>
  )
}
export default Lists